package com.tianci.appstore.controller;

import android.content.Context;
import android.content.Intent;
import android.os.RemoteException;

import com.coocaa.x.framework.app.CoocaaApplication;
import com.coocaa.x.framework.app.CoocaaApplication.PackageReceiver.InstallUninstallInterface;
import com.coocaa.x.framework.utils.Android;
import com.coocaa.x.framework.utils.LogUtils;
import com.coocaa.x.service.XServiceManager;
import com.coocaa.x.service.litedownloader.aidl.IDownloaderServiceListener;
import com.coocaa.x.service.litedownloader.data.DownloadError;
import com.coocaa.x.service.litedownloader.data.DownloadExtra;
import com.coocaa.x.service.litedownloader.data.DownloadTask;
import com.coocaa.x.service.litedownloader.data.ProcessInfo;
import com.skyworth.logsdk.appstore.LogAPIForAppStore;
import com.skyworth.webSDK.webservice.tcappstore.AppStoreBean;
import com.skyworth.webSDK.webservice.tcappstore.AppStoreException;
import com.skyworth.webSDK.webservice.tcappstore.AppZoneBean;
import com.tianci.appstore.R;
import com.tianci.appstore.dataprovider.AppDataProvider;
import com.tianci.appstore.ui.data.SkyAppDetailData.AppStatus;
import com.tianci.appstore.ui.data.SkyListAppData;
import com.tianci.appstore.ui.data.SkyListAppData.ListType;
import com.tianci.appstore.ui.data.SkyListStatusData;
import com.tianci.appstore.ui.gamezone.ZoneDataListener;
import com.tianci.appstore.ui.widget.TipToast;

import java.util.ArrayList;
import java.util.List;

public class AppStoreZoneController extends AppStoreBaseController implements
        InstallUninstallInterface {
    public static AppStoreZoneController instance = null;
    private Context mZoneContext = null;
    private ZoneDataListener mListener = null;

    public static AppStoreZoneController getInstance() {
        if (instance == null) {
            instance = new AppStoreZoneController(mContext);
        }
        return instance;
    }

    public AppStoreZoneController(Context c) {
        mZoneContext = c;
    }

    public void init() {
        CoocaaApplication.addPackageListener(this);
        runOnThread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                try {
                    XServiceManager.getDownloaderService().setListener(downloaderStub);
                } catch (RemoteException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }

    public void setZoneDataListener(ZoneDataListener listener) {
        mListener = listener;
    }

    public void getZoneInfo(final int zoneId) {
        runOnThread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                AppZoneBean zoneData = getZoneInfoFromeWeb(zoneId);
                String zoneCover = zoneData.zoneCover;
                boolean isOneKeySetup = false;
                List<AppStoreBean> list = zoneData.appList;
                isOneKeySetup = zoneData.isOneKeySetup;
                if (null == list || list.size() == 0) {
                    LogUtils.d("zone", "getZoneInfo--list is 0 or null-");
                    mListener.onZoneDataLoaded("", null, false);
                    TipToast.getInstance(mContext).showTipToast("获取后台数据为空！");
                    return;
                }
                List<SkyListAppData> appList = new ArrayList<SkyListAppData>();
                for (int i = 0; i < list.size(); i++) {
                    AppStoreBean bean = list.get(i);
                    SkyListStatusData data = new SkyListStatusData(ListType.CGY_APP_LIST);
                    data.setId(bean.id);
                    data.setIconUrl(bean.lmg);
                    data.setPkgName(bean.packagename);
                    data.setVersionName(bean.version);
                    data.setShowInfo(getString(R.string.downloaded_count)
                            + String.valueOf(bean.downloads));
                    data.setTitle(bean.name);
                    data.setExtra(bean.superscript); // 第一个角标
                    AppStatus status = AppStatus.NOT_DOWNLOADED;
                    status = AppDataProvider.getInstance().isAppInstalled(bean.packagename);
                    LogUtils.d("zone", "getZoneInfo--11-" + bean.name + " " + status.toString());
                    data.setStatus(status);
                    appList.add(data);
                }
                LogUtils.d("zone", "getZoneInfo---" + appList.size());
                mListener.onZoneDataLoaded(zoneCover, appList, isOneKeySetup);
            }
        });
    }

    public AppZoneBean getZoneInfoFromeWeb(int zoneId) {
        AppZoneBean zoneData = null;
        try {
            zoneData = CoocaaApplication.getCoocaaWebService().getAppStoreService().getZoneInfo(zoneId);
        } catch (AppStoreException e) {
            // TODO Auto-generated catch block
            LogAPIForAppStore.reportInterfaceError("根据专区id获取应用专区的数据", Android.throwable2String(e));
            LogUtils.d("lqw", "AppStoreException:" + e);
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    mListener.onZoneDataLoaded("", null, false);
                    TipToast.getInstance(mContext).showTipToast("获取后台数据超时！");
                }
            });

            e.printStackTrace();
        }
        return zoneData;
    }

    @Override
    public void destroy() {
        // TODO Auto-generated method stub
        CoocaaApplication.removePackageListener(this);
        runOnThread(new Runnable() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                try {
                    XServiceManager.getDownloaderService().clearListener(downloaderStub);
                } catch (RemoteException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }

    public void refreshZoneList(String pkg, AppStatus appStatus) {
        if (mListener != null && !pkg.equals("")) {
            LogUtils.d("intent", "refreshAppList--更新状态--" + pkg + " " + appStatus);
            mListener.onAppStatusChanged(pkg, appStatus);
        }
    }

    private IDownloaderServiceListener.Stub downloaderStub = new IDownloaderServiceListener.Stub() {

        @Override
        public void onReady(DownloadTask task) throws RemoteException {
            // TODO Auto-generated method stub
            DownloadExtra extra = DownloadExtra.parseJObject(task.extra, DownloadExtra.class);
            refreshZoneList(extra.pkgname, AppStatus.WAITING);
        }

        @Override
        public void onPrepare(DownloadTask task) throws RemoteException {
            // TODO Auto-generated method stub
        }

        @Override
        public void onStart(DownloadTask task) throws RemoteException {
            // TODO Auto-generated method stub
            DownloadExtra extra = DownloadExtra.parseJObject(task.extra, DownloadExtra.class);
            refreshZoneList(extra.pkgname, AppStatus.DOWNLOADING);
        }

        @Override
        public void onStop(DownloadTask task) throws RemoteException {
            // TODO Auto-generated method stub
            DownloadExtra extra = DownloadExtra.parseJObject(task.extra, DownloadExtra.class);
            refreshZoneList(extra.pkgname, AppStatus.DOWNLOAD_PAUSED);
        }

        @Override
        public void onProcessInfo(DownloadTask task, ProcessInfo info) throws RemoteException {
            // TODO Auto-generated method stub

        }

        @Override
        public void onFinish(DownloadTask task) throws RemoteException {
            // TODO Auto-generated method stub
            DownloadExtra extra = DownloadExtra.parseJObject(task.extra, DownloadExtra.class);
            refreshZoneList(extra.pkgname, AppStatus.DOWNLOADED);
        }

        @Override
        public void onError(DownloadTask task, DownloadError error) throws RemoteException {
            // TODO Auto-generated method stub

        }

        @Override
        public void onDelete(DownloadTask task) throws RemoteException {
            DownloadExtra extra = DownloadExtra.parseJObject(task.extra, DownloadExtra.class);
            boolean isInstalled = XServiceManager.getLitePMService().isInstalled(extra.pkgname);
            LogUtils.d("intent", "onDelete--isInstalled:" + isInstalled);
            if (!isInstalled)
                refreshZoneList(extra.pkgname, AppStatus.NOT_DOWNLOADED);
        }
    };

    @Override
    public void installEvent(Intent i) {
        // TODO Auto-generated method stub
        LogUtils.d("intent", "installEvent--pkg:" + i.getData().getSchemeSpecificPart());
        String pkg = i.getData().getSchemeSpecificPart();
        refreshZoneList(pkg, AppStatus.INSTALLED);
    }

    @Override
    public void uninstallEvent(Intent i) {
        // TODO Auto-generated method stub
        LogUtils.d("intent", "uninstallEvent--pkg:" + i.getData().getSchemeSpecificPart());
        String pkg = i.getData().getSchemeSpecificPart();
        refreshZoneList(pkg, AppStatus.NOT_DOWNLOADED);
    }
}
